﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint.Administration.Backup;
using Microsoft.SharePoint; 


namespace SharePointManagementStudio
{
    public partial class FrmPerformabackup : Form
    {
        public FrmPerformabackup()
        {
            InitializeComponent();
            backgroundWorker1.DoWork += new DoWorkEventHandler(backgroundWorker1_DoWork);
            backgroundWorker1.RunWorkerCompleted += new RunWorkerCompletedEventHandler(backgroundWorker1_RunWorkerCompleted);

        }

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {           
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                this.BeginInvoke(new MethodInvoker(delegate()
                {
                    foreach (string itm in listBoxWebApps.SelectedItems)
                    {
                        SPSite objSite = new SPSite(itm);
                        objSite.AllowUnsafeUpdates = true;
                        SPWeb web = objSite.OpenWeb();
                        web.AllowUnsafeUpdates = true;

                        SPSiteCollection mySiteCols = objSite.WebApplication.Sites;

                        string backupfielname = textBoxBackupLocations.Text + "\\" + createUniqfilename(itm) + ".bck";
                        appendText("Starting backup for " + itm.ToString() +"\n");  
                        mySiteCols.Backup(this.listBoxWebApps.SelectedItem.ToString(), @backupfielname, true);
                        appendText("Backup is complate for " + itm.ToString() + ". Backup file is located " + backupfielname +"\n");
                        objSite.Close();
                    }
                }));

                
            });
        }


        private void appendText(string p)
        {
            this.BeginInvoke(new MethodInvoker(delegate()
            {
                this.richTextBox1.Text += p;
            }));
        }

        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            toolStripProgressBar1.Value = 100;
            toolStripProgressBar1.Value = 0;
            timer1.Stop();
            this.buttonStart.Enabled = true;
            this.buttonChooseLocation.Enabled = false; 
        }
        private void toolStripButtonConnect_Click(object sender, EventArgs e)
        {
            SPFarm spf = SPFarm.Local;
            SPWebService spws = spf.Services.GetValue<SPWebService>("");
            int sitecount = spws.WebApplications.Count;

            foreach (SPWebApplication spwa in spws.WebApplications)
            {
                try
                {
                    this.listBoxWebApps.Items.Add(spwa.Sites[0].RootWeb.Url.ToString());
                }
                catch
                {
                    //   AppendText("error accured when connect to :" + spwa.Name.ToString() + " site collection is not found or site correpted.\n"); 
                }
            }
        }

        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            DialogResult result = this.folderBrowserDialog1.ShowDialog();
            if (result == DialogResult.OK)
            {
                this.textBoxBackupLocations.Text = this.folderBrowserDialog1.SelectedPath.ToString();
            }
        }

        private void buttonChooseLocation_Click(object sender, EventArgs e)
        {
            DialogResult result = this.folderBrowserDialog1.ShowDialog();
            if (result == DialogResult.OK)
            {
                this.textBoxBackupLocations.Text = this.folderBrowserDialog1.SelectedPath.ToString();
            }
        }

        private void listBoxWebApps_SelectedIndexChanged(object sender, EventArgs e)
        {


        }

        private string createUniqfilename(string s)
        {
            return  s.Substring(7)+"_" + DateTime.Now.Year.ToString()+ DateTime.Now.Month.ToString()+ DateTime.Now.Day.ToString();                 
        }

        private void buttonStart_Click(object sender, EventArgs e)
        {
            if (textBoxBackupLocations.Text != string.Empty)
            {
                if (listBoxWebApps.SelectedItems.Count > 0)
                {
                    this.buttonStart.Enabled = false;
                    this.buttonChooseLocation.Enabled = false;
                    this.timer1.Start();
                    this.backgroundWorker1.RunWorkerAsync();  
                }
                else
                {
                    MessageBox.Show("Select one ore more site collection to perform backup", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    richTextBox1.Text += "Select one ore more site collection to perform backup\n"; 
                }       
                
            }
            else
            {
                MessageBox.Show("Pleace Selecet a Backup Location","Warning",MessageBoxButtons.OK,MessageBoxIcon.Warning );
                richTextBox1.Text += "Pleace Selecet a Backup Location\n"; 
            }
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            if (toolStripProgressBar1.Value == toolStripProgressBar1.Maximum)
            {
                toolStripProgressBar1.Value = 0;
            }
            toolStripProgressBar1.PerformStep();
        }

     
    }
}